<?php
/**
 * Created by PhpStorm.
 * User: 沁塵
 * Date: 2019/4/20
 * Time: 19:57
 */

namespace app\api\controller\v1;

use app\api\model\LiveProductTask;
use app\api\model\LiveVoice;
use app\lib\doubao\Doubao;
use phpDocumentor\Reflection\Types\False_;
use think\Request;


class Ai
{
    public function models()
    {
        $directory = './sovit/models/';
        $items = scandir($directory);

        return  writeJson(200, $items, '获取所有的音色');
    }

    public function voice(Request $request)
    {
        set_time_limit(90);
        $params = $request->get();
        $model_name = $params['model_name'];
        $text = $params['text'];
        $speed_factor = $params['speed_factor'];
        $port = $params['port'];

        $prompt_text_path = './sovit/models/'.$model_name.'/'.$model_name.'.txt';
        $prompt_text = file_get_contents($prompt_text_path);

        $ip = "127.0.0.1";
        if($port == "9885" || $port == "9886" || $port == "9887"){
            $ip = "192.168.1.2";
        }


        $this->setGptWeights($model_name, $port,$ip);
        $this->setSovitsWeights($model_name, $port,$ip);
        // 拼出主播的请求链接
        $url = "http://".$ip.":".$port.'/tts';
        $pms = [
            "text" =>  $text,
            "text_lang" => "zh",
            "ref_audio_path" => 'models/'.$model_name.'/'.$model_name.'.wav',
            "prompt_lang" => "zh",
            "prompt_text" => $prompt_text,
            "text_split_method" => "cut0",
            "batch_size" => 20,
            "media_type" => "wav",
            "streaming_mode" => "False",
            "speed_factor" => $speed_factor,
            "repetition_penalty" => 1.35
        ];

        $queryString = http_build_query($pms);
        $fullUrl = $url . '?' . $queryString;

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $fullUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 20,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Accept: */*',
                'Host: f45k840659.zicp.vip:12109',
                'Connection: keep-alive',
                'Content-Description: File Transfer',
                'Content-Type: application/octet-stream' // 通用二进制文件类型

            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        echo $response;

    }

    public function setGptWeights($voice, $port,$ip)
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
        CURLOPT_URL => 'http://'.$ip.':'.$port.'/set_gpt_weights?weights_path=models/'.$voice.'/'.$voice.'.ckpt',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
        CURLOPT_CUSTOMREQUEST => 'GET',
        CURLOPT_HTTPHEADER => array(
            'User-Agent: Apifox/1.0.0 (https://apifox.com)'
        ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
//        echo $response;
        
    }

    public function setSovitsWeights($voice, $port,$ip)
    {
        $curl = curl_init();
        curl_setopt_array($curl, array(
            CURLOPT_URL => 'http://'.$ip.':'.$port.'/set_sovits_weights?weights_path=models/'.$voice.'/'.$voice.'.pth',
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 10,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'User-Agent: Apifox/1.0.0 (https://apifox.com)'
            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
//        echo $response;
    }

    public function textRefresh(Request $request)
    {
        $params = $request->get();
        $num = $params['num'];
        $text = $params['text'];

        $res = (new Doubao())->textRefresh($text,$num);

        return writeJson(200, $res, '获取新的描述');
    }


    public function teaseapart(Request $request)
    {
        set_time_limit(90);
        $params = $request->post();
        $num = $params['num'];
        $text = $params['text'];

        $res = (new Doubao())->teaseapart($text,$num);

        return writeJson(200, $res, '获取新的描述');
    }

    public function titleRefresh(Request $request)
    {
        $params = $request->get();
        $num = $params['num'];
        $text = $params['text'];

        $res = (new Doubao())->titleRefresh($text,$num);

        return writeJson(200, $res, '获取新的描述');
    }

    public function ksVoice(Request $request)
    {
        $params = $request->post();

        $task = LiveProductTask::where("tname", trim($params["tname"]))->findOrEmpty();
        $voice = LiveVoice::where("voice", $task["fb_voice"])->findOrEmpty();
        $model_name = $task["fb_voice"];
        $speed_factor = $voice["guang_speed"];
        $prompt_text_path = './sovit/models/'.$model_name.'/'.$model_name.'.txt';
        $prompt_text = file_get_contents($prompt_text_path);
        $port = 9880;
        $ip = "127.0.0.1";
        $this->setGptWeights($model_name, $port,$ip);
        $this->setSovitsWeights($model_name, $port,$ip);

        // 拼出主播的请求链接
        $url = "http://".$ip.":".$port.'/tts';
        $pms = [
            "text" =>  $params["text"],
            "text_lang" => "zh",
            "ref_audio_path" => 'models/'.$model_name.'/'.$model_name.'.wav',
            "prompt_lang" => "zh",
            "prompt_text" => $prompt_text,
            "text_split_method" => "cut0",
            "batch_size" => 20,
            "media_type" => "wav",
            "streaming_mode" => "False",
            "speed_factor" => $speed_factor,
            "repetition_penalty" => 1.35
        ];

        $queryString = http_build_query($pms);
        $fullUrl = $url . '?' . $queryString;

        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $fullUrl,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => '',
            CURLOPT_MAXREDIRS => 20,
            CURLOPT_TIMEOUT => 0,
            CURLOPT_FOLLOWLOCATION => true,
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => 'GET',
            CURLOPT_HTTPHEADER => array(
                'Accept: */*',
                'Host: f45k840659.zicp.vip:12109',
                'Connection: keep-alive',
                'Content-Description: File Transfer',
                'Content-Type: application/octet-stream' // 通用二进制文件类型

            ),
        ));

        $response = curl_exec($curl);

        curl_close($curl);
        echo $response;
    }

    public function trans(Request $request)
    {
        $params = $request->post();

        $url = "http://localhost:7897/run/convert_audio_url";

        $payload = array(
            "data" => array(
                $params["audio"],$params["sex"]
//                "https://www.youdnr.cn/3d7fd1f07dd2d288988d4798e54c9ec520250519164903.mp3",
//                "女"
            )
        );

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, 30);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen(json_encode($payload))
        ));

        $response = curl_exec($ch);

        curl_close($ch);
        echo $response;

    }
}